//
//  FriendDetail.swift
//  AppleDemo
//
//  Created by Just 花语 on 2025/10/28.
//

import SwiftUI
import SwiftData
struct FriendDetail:View{
    @Bindable var friend:FriendIn5
    @Query(sort:\Movie.title) private var movies:[Movie]
    let isNew:Bool
    @Environment(\.dismiss) private var dismiss
    @Environment(\.modelContext) private var context
    
    init(friend: FriendIn5,isNew:Bool = false) {
        self.friend = friend
        self.isNew = isNew
    }
    var body: some View{
        Form{
            TextField("Name",text: $friend.name)
                .autocorrectionDisabled()
            Picker("Favorite Movie",selection: $friend.favoriteMovie){
                Text("None").tag(nil as Movie?)
                ForEach(movies){ movie in
                    Text(movie.title).tag(movie as Movie?)
                }
            }
            .pickerStyle(.menu)
        }
        .navigationTitle(isNew ? "New Friend":"Friend")
        .navigationBarTitleDisplayMode(.inline)
        .toolbar{
            if isNew{
                ToolbarItem(placement: .confirmationAction) {
                   Button("Save") {
                       dismiss()
                   }
               }
                ToolbarItem(placement: .cancellationAction) {
                   Button("Cancel") {
                       context.delete(friend)
                       dismiss()
                   }
               }
            }
        }
    }
}
#Preview {
    NavigationStack{
        FriendDetail(friend: SampleData.shared.friend,isNew: true)
    }
}

